package com.example.behaviour.customization.observer.multicaster;

import com.example.behaviour.customization.observer.event.AppEvent;
import com.example.behaviour.customization.observer.listener.AppListener;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SimpleAppEventMulticaster extends AbstractAppEventMulticaster {

    private Executor executor = new ThreadPoolExecutor(
            10,15,60, TimeUnit.SECONDS,new LinkedBlockingDeque<>(100)
    );
    // 通知
    @Override
    public void multicasterEvent(AppEvent event) {
        // 拿到需要通知的集合
        // 挨次通知
        for (AppListener listener : getAppListeners(event)) {
            if (executor != null){
                executor.execute(()->{
                    invokeListener(listener,event);
                });
            }else{
                invokeListener(listener,event);
            }
        }
    }

    private void invokeListener(AppListener listener, AppEvent event) {
        try {
            listener.onAppEvent(event);
        } catch (Exception e) {
            e.printStackTrace();
            // 不同的异常处理机制
        }
    }
}
